<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="950" @ok="handleSubmit">
      <BasicForm @register="registerForm" ref="formRef">
        <template #buildSlot="{ model, field }">
                <a-select
                    v-model:value="model[field]" @change="buildChange"
                    style="width: 180px" :fieldNames="{label:'buildName',value:'id' }"
                    :options="buildOptions"
                >
                </a-select>
        </template>
        <template #storeySlot="{ model, field }">
                <a-select
                    v-model:value="model[field]" @change="storeyChange"
                    style="width: 180px" :fieldNames="{label:'storeyName',value:'id' }"
                    :options="storeyOptions"
                >
                </a-select>
        </template>
        <template #managerIdSlot="{ model, field }">
               <JSelectDormManPerson v-model:value="model[field]" :buildId="buildId" componentProps="{labelKey: 'name'}" ></JSelectDormManPerson>
        </template>
        <!-- <template #roomSlot="{ model, field }">
                <a-select
                    v-model:value="model[field]" @change="roomChange"
                    style="width: 180px" :fieldNames="{label:'ruleName',value:'ruleId' }"
                    :options="roomOptions"
                >
                </a-select>
        </template> -->
      </BasicForm>
  <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="宿舍床铺信息" key="dormBed" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="dormBed"
          :loading="dormBedTable.loading"
          :columns="dormBedTable.columns"
          :dataSource="dormBedTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
        >
           <template #myAction="props">
              <a-button @click="bedRemoved(props)" style="margin-right:5px;">删除</a-button>
              <a-button v-if="isUpdate&&props.row.createTime&&props.row.status==0" @click="handleBedStatus(props,'1')" style="margin-right:5px;">启用</a-button>
              <a-button v-if="isUpdate&&props.row.createTime&&props.row.status==1" @click="handleBedStatus(props,'0')">停用</a-button>
            </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref,reactive} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import { JVxeTable } from '/@/components/jeecg/JVxeTable'
    import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts'
    import {formSchema,dormBedColumns} from '../DormRoom.data';
    import {saveOrUpdate,dormBedList,switchBedStatus,deleteBed,buildList,storeyList,roomList} from '../DormRoom.api';
    import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils'
    import JSelectDormManPerson from '/@/components/Form/src/jeecg/components/JSelectDormManPerson.vue';

    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const formDisabled = ref(false);
    const refKeys = ref(['dormBed', ]);
    const activeKey = ref('dormBed');
    const dormBed = ref();
    const rowId = ref('');
    const tableRefs = {dormBed, };
    const buildId = ref('');

    const dormBedTable = reactive({
          loading: false,
          dataSource: [],
          columns:dormBedColumns
    })
    let buildOptions= ref([])
    let storeyOptions= ref([])
    let roomOptions= ref([])
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
     //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await reset();
        setModalProps({confirmLoading: false,showCancelBtn:data?.showFooter,showOkBtn:data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        formDisabled.value = !data?.showFooter;
        getBuildOptions()
        getStoreyOptions()
        if (unref(isUpdate)) {

            rowId.value = data.record.id
            console.log( data.record);
            data.record.buildId = Number(data.record.buildId)
			buildId.value=String(data.record.buildId)
            data.record.storeyId = Number(data.record.storeyId)
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
             requestSubTableData(dormBedList, {id:data?.record?.id}, dormBedTable)
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //方法配置
    const [handleChangeTabs,handleSubmit,requestSubTableData,formRef] = useJvxeMethod(requestAddOrEdit,classifyIntoFormData,tableRefs,activeKey,refKeys);
    async function buildChange(e){
        buildId.value = e
       await setFieldsValue({
               storeyId:'',
              //  roomCode: ''
        })
        // roomOptions.value = []
        getStoreyOptions(e)
    }
    async function storeyChange(e){
      //  await setFieldsValue({
      //          roomCode: ''
      //   })
      // getRoomOptions(e)
    }
    async function roomChange(e){
      
    }
    function getBuildOptions(){
        buildList({
            status:1,
            pageSize:100,
        }).then(res=>{
          buildOptions.value = res.records
        })
    }
    function getStoreyOptions(e){
      storeyList({
        buildId:e? e : '',
        status:1,
        pageSize:100,
      }).then(res=>{
        storeyOptions.value = res.records
      })
    }
    // function getRoomOptions(e){
    //   roomList({
    //     id:e? e : ''
    //   }).then(res=>{
    //     roomOptions.value = res

    //   })
    // }

    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

    function handleBedStatus(e,status){
      // console.log(e);
      if(e.row.createTime){
          switchBedStatus({
            id: e.rowId,
            status,
          }).then(res=>{
             requestSubTableData(dormBedList, {id:rowId.value}, dormBedTable)
          })
      }else{
      }
    }
    function bedRemoved(e){
      // console.log(e);
      if(e.row.createTime){
          deleteBed({
            id: e.rowId
          }).then(res=>{
             requestSubTableData(dormBedList, {id:rowId.value}, dormBedTable)
          })
      }else{
        dormBed.value?.removeRows(e.row, true);
      }

    }
    async function reset(){
      await resetFields();
      activeKey.value = 'dormBed';
      dormBedTable.dataSource = [];
    }
    function classifyIntoFormData(allValues) {
         let main = Object.assign({}, allValues.formValue)
         return {
           ...main, // 展开
           dormBedList: allValues.tablesValue[0].tableData,
         }
       }
    //表单提交事件
    async function requestAddOrEdit(values) {
        try {
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(values, isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
    :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>